import { defineStore } from 'pinia'
import { DCYX_DICTATION_API } from '@/api/dcyx/dictation.api'
import type {
  WordItem,
  DictationRecord,
  UnitDictationStatus,
  DictationRecordUpdate,
  UnitDictationStats,
} from '@/api/dcyx/dictation.api'
import { useDcyxUserStoreHook } from './dcyx_user.store'

export const useDcyxDictationStore = defineStore('dcyx_dictation', () => {
  const wordList = ref<WordItem[]>([])
  const unitDictationStatus = ref<UnitDictationStatus | null>(null)
  const dictationRecords = ref<DictationRecord[]>([])
  const dictationRecordsTotal = ref(0)

  // 获取听写单词列表
  const fetchDictationWords = async (unitId: number) => {
    return new Promise<WordItem[]>((resolve, reject) => {
      const params = {
        unitId,
        pageNum: 1,
        pageSize: 1000,
      }
      DCYX_DICTATION_API.getDictationWords(params)
        .then((res) => {
          wordList.value = res.list
          resolve(res.list)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 更新听写学习记录
  const updateDictationRecord = async (data: DictationRecordUpdate) => {
    return new Promise<void>((resolve, reject) => {
      DCYX_DICTATION_API.updateDictationRecord(data)
        .then(() => {
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 获取听写学习记录
  const fetchDictationRecords = async (params: {
    pageNum: number
    pageSize: number
    wordId?: number
    userId?: number
    unitId?: number
  }) => {
    return new Promise<{ list: DictationRecord[]; total: number }>(
      (resolve, reject) => {
        DCYX_DICTATION_API.getDictationRecords(params)
          .then((res) => {
            dictationRecords.value = res.list
            dictationRecordsTotal.value = res.total
            resolve({ list: res.list, total: res.total })
          })
          .catch((error) => {
            reject(error)
          })
      },
    )
  }

  // 更新单元听写状态
  const updateUnitDictationStatus = async (data: UnitDictationStatus) => {
    console.log('updateUnitDictationStatus data', data)
    return new Promise<void>((resolve, reject) => {
      DCYX_DICTATION_API.updateUnitDictationStatus(data)
        .then(() => {
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 更新单元听写统计
  const updateUnitDictationStats = async (data: UnitDictationStats) => {
    console.log('updateUnitDictationStats data', data)
    return new Promise<void>((resolve, reject) => {
      DCYX_DICTATION_API.updateUnitDictationStats(data)
        .then(() => {
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 获取单元听写状态
  const fetchUnitDictationStatus = async (unitId: number) => {
    return new Promise<UnitDictationStatus | null>((resolve, reject) => {
      const userId = useDcyxUserStoreHook().userInfo.id
      const params = {
        unitId,
        userId,
      }
      DCYX_DICTATION_API.getUnitDictationStatus(params)
        .then((res) => {
          const status = res.list && res.list.length > 0 ? res.list[0] : null
          unitDictationStatus.value = status
          resolve(status)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 播放单词音频
  const playWordAudio = async (word: string): Promise<string> => {
    return new Promise<string>((resolve, reject) => {
      // 复用memory API的音频功能
      import('@/api/dcyx/memory.api').then(({ DCYX_MEMORY_API }) => {
        DCYX_MEMORY_API.getWordAudio(word)
          .then((blob) => {
            const realBlob = blob instanceof Blob ? blob : blob.data
            const url = URL.createObjectURL(realBlob)
            resolve(url)
          })
          .catch((error) => {
            reject(error)
          })
      })
    })
  }

  return {
    wordList,
    unitDictationStatus,
    dictationRecords,
    dictationRecordsTotal,
    fetchDictationWords,
    updateDictationRecord,
    fetchDictationRecords,
    updateUnitDictationStatus,
    fetchUnitDictationStatus,
    playWordAudio,
    updateUnitDictationStats,
  }
})
